const express = require('express');
const CryptoJs = require('crypto-js');
const UserModel = require('../models/user');
const { getToken } = require('../utils/token');
const { Message,MessageList } = require('../utils/message');

const router = express.Router();

router.post('/', (req, res, next) => {
  const {username, password} = req.body;
  UserModel.findOne({ username }).then(data => {
    if(data) {
      if(data.role=='normal'){
        if (CryptoJs.MD5(password).toString() !== data.password) {
          res.json(Message(400,'用户名或密码错误！',))
          return
        }
      }else{
        if (password !== data.password) {
          res.json(Message(400,'用户名或密码错误！',))
          return
        }
      }
      delete data._doc.password;
      const token = getToken({ _id: data._id,username: data.username})
      const userInfo={ ...data._doc, token }
      res.json(Message(200,'登录验证成功',userInfo))
      return
    }else{
      res.json(Message(400,'用户名或密码错误！'))
    }
  })
})

module.exports = router;